package com.shqcjd.sinopecdemomobile.ui.activity.maintain;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.eventbus.RefreshData;
import com.shqcjd.sinopecdemomobile.model.pojo.AppOperationGuideMode;
import com.shqcjd.sinopecdemomobile.model.pojo.GuidePhoto;
import com.shqcjd.sinopecdemomobile.model.pojo.TreeNode;
import com.shqcjd.sinopecdemomobile.ui.activity.problem.ProblemFeedbackActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.tipwizard.TipWizardImageActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.tipwizard.TipWizardVideoActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.AlbumUtils;
import com.shqcjd.sinopecdemomobile.util.MyGlideEngine;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;
import com.shqcjd.sinopecdemomobile.widget.MaintainAbnormalDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 维修指导
 */
public class MaintainDetailActivity extends BaseActivity {

    private final int IMAGE_FILE_RESULT_CODE = 2;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_feedback_btn)
    TextView tvFeedbackBtn;
    @BindView(R.id.tv_video_btn)
    TextView tvVideoBtn;
    @BindView(R.id.tv_img_btn)
    TextView tvImgBtn;
    @BindView(R.id.tv_finish_btn)
    TextView tvFinishBtn;
    @BindView(R.id.button_description)
    TextView tvButtonDesc;
    @BindView(R.id.tv_confirm)
    View btn;
    @BindView(R.id.image_pz)
    ImageView pzView;
    @BindView(R.id.tv_info)
    TextView tv_info;

    private AppOperationGuideMode.ItemsBean node;
    private int stepDetailId;

    private int nextId,prevId;
    private boolean need_img;

    private MaintainAbnormalDialog abnormalDialog;
    private Context mContext;
    private String kks;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_maintain_detail;
    }


    @OnClick({R.id.tv_feedback_btn, R.id.tv_video_btn, R.id.tv_img_btn, R.id.tv_finish_btn,R.id.tv_confirm,R.id.next_btn,R.id.prev_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_feedback_btn://意见反馈
                Intent it = new Intent(this, ProblemFeedbackActivity.class);
                it.putExtra("taskId", node.workTaskId+"");
                it.putExtra("projectName", node.equipmentTypeName);
                it.putExtra("kks", kks);
                startActivity(it);
                break;
            case R.id.tv_video_btn://视频
                if (stepDetailId!=0){
                    Intent intent = new Intent(this,TipWizardVideoActivity.class);
                    intent.putExtra("stepDetailId",stepDetailId);
                    startActivity(intent);
                }

                break;
            case R.id.tv_img_btn://图片
                if (stepDetailId!=0){
                    Intent intent = new Intent(this,TipWizardImageActivity.class);
                    intent.putExtra("stepDetailId",stepDetailId);
                    startActivity(intent);
                }

                break;
            case R.id.tv_finish_btn:
                finish();
                break;
            case R.id.tv_confirm:
                if (need_img){
                    showUploadDialog();
                }else {
                    if (nextId==0){
                        taskComplete();
                        return;
                    }
                    nextStep();
                }

                break;
            case R.id.next_btn:
                if (nextId==0){
                    ToastUtils.showShort(MaintainDetailActivity.this,"已经是最后一步");
                    return;
                }
                nextStep();
                break;
            case R.id.prev_btn:
                if (prevId==0){
                    ToastUtils.showShort(MaintainDetailActivity.this,"已经是第一步");
                    return;
                }
                prevStep();
                break;
        }
    }

    @Override
    public void initView() {
        super.initView();
        mContext = this;

        node = (AppOperationGuideMode.ItemsBean) getIntent().getSerializableExtra("data");
        showWaitingDialog("正在获取数据");
        ApiService.repairStepDetail(node.currentStepId,node.workTaskId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<TreeNode.StepDetail>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<TreeNode.StepDetail> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            kks = retData.data.kks;
                            tvContent.setText(retData.data.step_detail_content);
                            tv_info.setText(retData.data.step_detail_standard);
                            stepDetailId = retData.data.id;
                            nextId = retData.data.nextId;
                            prevId = retData.data.prevId;
                            if (nextId==0){
                                tvButtonDesc.setText("结束");
                            }
                            need_img=retData.data.need_img;
                            pzView.setVisibility(need_img?View.VISIBLE:View.GONE);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    /**
     * 上传多图
     * @param mList
     */
    private void loadMultiFile(List<String> mList,String tip) {
        List<File> files = new ArrayList<>();
        for (String uri : mList) {
            files.add(new File(uri));
        }
        ApiService.uploadMultiImg(files)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<String>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("上传图片中");
                    }

                    @Override
                    public void _onNext(ResponseData<List<String>> retData) {
                        if (retData.retCode == 10000) {
                            putPhoto(retData.data,tip);
                        } else {
                            ToastUtils.showShort(MaintainDetailActivity.this,"上传失败");
                            hideWaitingDialog();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(MaintainDetailActivity.this,errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                    }
                });
    }

    private void putPhoto(List<String> data,String tip){
        GuidePhoto bean = new GuidePhoto();
        bean.description = tip;
        bean.img = data;
        bean.stepId = stepDetailId;
        bean.workOrderTaskId = node.workTaskId;
        Gson gson = new Gson();
        ApiService.getRepairPutPhoto(gson.toJson(bean))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Object>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);

                    }

                    @Override
                    public void _onNext(ResponseData<Object> retData) {
//                        taskComplete();
                        if (retData.retCode == 10000) {
                            nextStep();
                        } else {
                            ToastUtils.showShort(mContext,"上传失败");
                        }

                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(MaintainDetailActivity.this,errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }


    public void RequestLocationAndCallPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Matisse.from(MaintainDetailActivity.this)
                                    .choose(MimeType.ofImage()) // 选择 mime 的类型
                                    .countable(false)
                                    .maxSelectable(4) // 图片选择的最多数量
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f) // 缩略图的比例
                                    .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                                    .theme(R.style.Matisse_Zhihu)
                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(true, getPackageName()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .forResult(IMAGE_FILE_RESULT_CODE); // 设置作为标记的请求码
                        } else {

                        }
                    }
                });
    }



    private void showUploadDialog() {
        if(abnormalDialog==null){
            abnormalDialog = new MaintainAbnormalDialog(MaintainDetailActivity.this);
            abnormalDialog.setOnBtnClickListener(new MaintainAbnormalDialog.OnBtnClickListener() {
                @Override
                public void onBtnClick(View view, List<String> mList) {
                    if (mList.size() > 0) {
                        loadMultiFile(mList,abnormalDialog.et_dialog_abnormal.getText().toString());
                        abnormalDialog.dismiss();
                    }

                }
            });
            abnormalDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {

                }
            });
        }
        if(!abnormalDialog.isShowing()){
            abnormalDialog.cleanList();
            abnormalDialog.show();
        }
    }


    private void showGoodDialog(){
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.layout_good, false)
                .show();
        dialog.findViewById(R.id.good_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                doGood();
            }
        });
        dialog.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                EventBus.getDefault().post(new RefreshData());
                finish();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
    }

    private void doGood(){
        showWaitingDialog("正在获取数据");
        ApiService.doGood(node.equipmentTypeId,node.guideType)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> retData) {
                        if (retData.retCode == 10000 ) {
                            ToastUtils.showShort(MaintainDetailActivity.this,"谢谢您的点赞！");
                            EventBus.getDefault().post(new RefreshData());
                            finish();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putSerializable("data",node);

    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        node = (AppOperationGuideMode.ItemsBean) savedInstanceState.getSerializable("data");
    }

    private void taskComplete(){
        showWaitingDialog("正在获取数据");
        ApiService.repairTaskComplete(node.workTaskId,node.currentStepId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> retData) {
                        if (retData.retCode == 10000 && retData.data == 1) {
                            showGoodDialog();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }



    private void nextStep(){
        showWaitingDialog("正在获取数据");
        ApiService.repairNextStepDetail(stepDetailId,node.workTaskId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<TreeNode.StepDetail>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<TreeNode.StepDetail> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            kks = retData.data.kks;
                            tvContent.setText(retData.data.step_detail_content);
                            tv_info.setText(retData.data.step_detail_standard);
                            stepDetailId = retData.data.id;
                            nextId = retData.data.nextId;
                            prevId = retData.data.prevId;
                            if (nextId == 0) {
                                tvButtonDesc.setText("结束");
                            }
                            need_img = retData.data.need_img;
                            pzView.setVisibility(need_img ? View.VISIBLE : View.GONE);
                        } else if (retData.retCode == 24002) {//需要拍照
                            ToastUtils.showShort(mContext,retData.retMsg);
                        } else if (retData.retCode == 24001) {//步骤不存在 完成
                            taskComplete();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void prevStep(){
        showWaitingDialog("正在获取数据");
        ApiService.repairPrevStepDetail(stepDetailId, node.workTaskId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<TreeNode.StepDetail>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<TreeNode.StepDetail> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            kks = retData.data.kks;
                            tvContent.setText(retData.data.step_detail_content);
                            tv_info.setText(retData.data.step_detail_standard);
                            stepDetailId = retData.data.id;
                            nextId = retData.data.nextId;
                            prevId = retData.data.prevId;
                            tvButtonDesc.setText("确定");
                            need_img=retData.data.need_img;
                            pzView.setVisibility(need_img?View.VISIBLE:View.GONE);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_FILE_RESULT_CODE && resultCode == RESULT_OK) {
            //图片上传
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    try {
                        String albumStringPath = AlbumUtils.getRealFilePath(this, uri);
                        abnormalDialog.addPic(albumStringPath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }


}
